<template>
  <div class="app-container">
    <ContentWrap>
      <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
        <el-form-item label="策略名称" prop="strategyName">
          <el-input
            v-model="queryParams.strategyName"
            placeholder="请输入策略名称"
            clearable
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>

      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button
            type="primary"
            plain
            icon="el-icon-plus"
            size="mini"
            @click="handleAdd"
            v-hasPermi="['params:strategyParams:add']"
          >新增
          </el-button>
        </el-col>
        <!--      <el-col :span="1.5">-->
        <!--        <el-button-->
        <!--          type="success"-->
        <!--          plain-->
        <!--          icon="el-icon-edit"-->
        <!--          size="mini"-->
        <!--          :disabled="single"-->
        <!--          @click="handleUpdate"-->
        <!--          v-hasPermi="['params:strategyParams:edit']"-->
        <!--        >修改-->
        <!--        </el-button>-->
        <!--      </el-col>-->
        <!--      <el-col :span="1.5">-->
        <!--        <el-button-->
        <!--          type="danger"-->
        <!--          plain-->
        <!--          icon="el-icon-delete"-->
        <!--          size="mini"-->
        <!--          :disabled="multiple"-->
        <!--          @click="handleDelete"-->
        <!--          v-hasPermi="['params:strategyParams:remove']"-->
        <!--        >删除-->
        <!--        </el-button>-->
        <!--      </el-col>-->
        <el-col :span="1.5">
          <el-button
            type="warning"
            plain
            icon="el-icon-download"
            size="mini"
            @click="handleExport"
            v-hasPermi="['params:strategyParams:export']"
          >导出
          </el-button>
        </el-col>
        <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
      </el-row>

      <el-table v-loading="loading" :data="strategyParamsList" border @selection-change="handleSelectionChange"
                :height="getAvailableHeight">
        <!--      <el-table-column type="selection" width="55" align="center"/>-->
        <el-table-column type="index" width="40" align="center" label="#" :fixed="true"/>
        <el-table-column label="策略名称" align="center" prop="strategyName" width="200"/>
        <el-table-column label="目标类型" align="center" prop="targetType" width="90">
          <template slot-scope="scope">
            <dict-tag :options="dict.type.warn_target_type" :value="scope.row.targetType"/>
          </template>
        </el-table-column>
        <el-table-column label="参数类型" align="center" prop="paramType" width="160">
          <template slot-scope="scope">
            <dict-tag :options="dict.type.warn_param_type" :value="scope.row.paramType"/>
          </template>
        </el-table-column>
        <el-table-column label="是否通用" align="center" prop="isGeneral" width="80">
          <template slot-scope="scope">
            <el-tag :type="['danger', 'success'][scope.row.isGeneral]">{{ ['否', '是'][scope.row.isGeneral] }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="报警对象" align="center" prop="targetId" width="115">
          <template slot-scope="scope">
            <span v-if="scope.row.targetId">{{ scope.row.targetName }}</span>
            <span v-else>
            {{
                ['全部大分区', '全部DMA分区', '全部大用户', '全部大表设备'][scope.row.targetType - 1]
              }}</span>
          </template>
        </el-table-column>
        <el-table-column label="起始日期" align="center" prop="startDate" width="100">
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.startDate, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="截止日期" align="center" prop="endDate" width="100">
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.endDate, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="起始时间" align="center" prop="startTime" width="90">
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.startTime, '{h}:{i}:{s}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="截止时间" align="center" prop="endTime" width="90">
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.endTime, '{h}:{i}:{s}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="一级上限限制值" align="center" prop="level1Up" width="115"/>
        <el-table-column label="一级下限限制值" align="center" prop="level1Down" width="115"/>
        <el-table-column label="二级上限限制值" align="center" prop="level2Up" width="115"/>
        <el-table-column label="三级上限限制值" align="center" prop="level3Up" width="115"/>
        <el-table-column label="是否启用" align="center" prop="enable" width="80">
          <template slot-scope="scope">
            <el-tag :type="['danger', 'success'][scope.row.enable]">{{ ['否', '是'][scope.row.enable] }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="备注" prop="remark" width="220"/>
        <el-table-column label="操作" align="center" width="110" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              icon="el-icon-edit"
              @click="handleUpdate(scope.row)"
              v-hasPermi="['params:strategyParams:edit']"
            >修改
            </el-button>
            <el-button
              size="mini"
              type="text"
              icon="el-icon-delete"
              @click="handleDelete(scope.row)"
              v-hasPermi="['params:strategyParams:remove']"
            >删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination
        :total="total"
        :page-sizes="[15, 30, 45, 60]"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
      />

      <!-- 添加或修改报警策略对话框 -->
      <el-dialog :title="title" :visible.sync="open" width="800px" :close-on-click-modal="false" append-to-body>
        <el-form ref="form" :model="form" :rules="rules" label-width="125px">
          <el-form-item label="策略名称" prop="strategyName">
            <el-input v-model="form.strategyName" placeholder="请输入策略名称"/>
          </el-form-item>

          <el-row>
            <el-col :span="12">
              <el-form-item label="目标类型" prop="targetType">
                <el-select v-model="form.targetType" placeholder="请选择目标类型" style="width: 100%;"
                           @change="handleTargetTypeChange">
                  <el-option v-for="dict in dict.type.warn_target_type"
                             :key="dict.value" :label="dict.label" :value="dict.value"/>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="参数类型" prop="paramType">
                <el-select v-model="form.paramType" placeholder="请选择目标类型" style="width: 100%;"
                           v-if="form.targetType === '1'">
                  <el-option v-for="(dict,index) in dict.type.warn_param_type" v-if="index === 1"
                             :key="dict.value" :label="dict.label" :value="dict.value"/>
                </el-select>
                <el-select v-model="form.paramType" placeholder="请选择目标类型" style="width: 100%;"
                           v-if="form.targetType === '2'">
                  <el-option v-for="(dict,index) in dict.type.warn_param_type" v-if="index === 1 || index === 2"
                             :key="dict.value" :label="dict.label" :value="dict.value"/>
                </el-select>
                <el-select v-model="form.paramType" placeholder="请选择目标类型" style="width: 100%;"
                           v-if="form.targetType === '3'">
                  <el-option v-for="(dict,index) in dict.type.warn_param_type" v-if="index === 0"
                             :key="dict.value" :label="dict.label" :value="dict.value"/>
                </el-select>
                <el-select v-model="form.paramType" placeholder="请选择目标类型" style="width: 100%;"
                           v-if="form.targetType === '4'">
                  <el-option v-for="(dict,index) in dict.type.warn_param_type" v-if="index > 2"
                             :key="dict.value" :label="dict.label" :value="dict.value"/>
                </el-select>
                <el-select v-model="form.paramType" placeholder="请选择目标类型" style="width: 100%;"
                           v-if="form.targetType == undefined">
                  <el-option v-for="dict in dict.type.warn_param_type"
                             :key="dict.value" :label="dict.label" :value="dict.value"/>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row>
            <el-col :span="12">
              <el-form-item label="是否通用" prop="isGeneral">
                <el-radio-group v-model="form.isGeneral" placeholder="请选择">
                  <el-radio :label="1">是</el-radio>
                  <el-radio :label="0">否</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="报警对象" prop="targetId">
                <el-input v-model="form.targetId" :disabled="form.isGeneral===1">
                  <el-button slot="append" @click="handleTargetIdSelectClick">选择</el-button>
                </el-input>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row>
            <el-col :span="12">
              <el-form-item label="起始日期" prop="StartDate">
                <el-date-picker clearable
                                v-model="form.StartDate"
                                type="date"
                                format="yyyy-MM-dd"
                                value-format="yyyy-MM-dd"
                                style="width: 100%;"
                                placeholder="请选择起始日期">
                </el-date-picker>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="截止日期" prop="EndDate">
                <el-date-picker clearable
                                v-model="form.EndDate"
                                type="date"
                                format="yyyy-MM-dd"
                                value-format="yyyy-MM-dd"
                                style="width: 100%;"
                                placeholder="请选择截止日期">
                </el-date-picker>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row>
            <el-col :span="12">
              <el-form-item label="起始时间" prop="StartTime">
                <el-time-picker clearable
                                v-model="form.StartTime"
                                value-format="yyyy-MM-dd HH:mm:ss"
                                style="width: 100%;"
                                placeholder="请选择起始时间">
                </el-time-picker>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="截止时间" prop="EndTime">
                <el-time-picker clearable
                                v-model="form.EndTime"
                                value-format="yyyy-MM-dd HH:mm:ss"
                                style="width: 100%;"
                                placeholder="请选择截止时间">
                </el-time-picker>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row>
            <el-col :span="12">
              <el-form-item label="一级上限限制值" prop="level1Up">
                <el-input v-model="form.level1Up" placeholder="请输入一级上限限制值"/>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="一级下限限制值" prop="level1Down">
                <el-input v-model="form.level1Down" placeholder="请输入一级下限限制值"/>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row>
            <el-col :span="12">
              <el-form-item label="二级上限限制值" prop="level2Up">
                <el-input v-model="form.level2Up" placeholder="请输入二级上限限制值"/>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="三级上限限制值" prop="level3Up">
                <el-input v-model="form.level3Up" placeholder="请输入三级上限限制值"/>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row>
            <el-col :span="12">
              <el-form-item label="是否启用" prop="enable">
                <el-radio-group v-model="form.enable" placeholder="请选择">
                  <el-radio :label="1">是</el-radio>
                  <el-radio :label="0">否</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="备注" prop="remark">
                <el-input v-model="form.remark" type="textarea" :rows="3" placeholder="请输入备注"/>
              </el-form-item>
            </el-col>
          </el-row>

        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </el-dialog>

      <RegionSingleSelector ref="refStrategyRegionSingleSelector" :callback="handleRegionSelected"/>
      <AllTerminalSelector ref="refStrategyAllTerminalSelector" :callback="handleTerminalSelected"/>
    </ContentWrap>
  </div>
</template>

<script>
import {
  listStrategyParams,
  getStrategyParams,
  delStrategyParams,
  addStrategyParams,
  updateStrategyParams
} from "@/api/leakage/strategyParams";
import RegionSingleSelector from '../../../components/RegionSingleSelector'
import AllTerminalSelector from '../../../components/AllTerminalSelector'

export default {
  name: "StrategyParams",
  components: {
    RegionSingleSelector,
    AllTerminalSelector,
  },
  dicts: ['warn_target_type', 'warn_param_type'],
  data() {
    return {
      screenHeight: null,
      // 遮罩层
      loading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 报警策略表格数据
      strategyParamsList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 15,
        tenantId: null,
        strategyName: null,
        targetType: null,
        paramType: null,
        isGeneral: null,
        targetId: null,
        startDate: null,
        endDate: null,
        startTime: null,
        endTime: null,
        level1Up: null,
        level1Down: null,
        level2Up: null,
        level3Up: null,
        enable: null,
        remark: null
      },
      // 表单参数
      form: {
        isGeneral: 1,
        enable: 1,
        StartTime: '2022-02-02 00:00:00',
        EndTime: '2022-02-02 23:59:59'
      },
      // 表单校验
      rules: {
        strategyName: [
          {required: true, message: "请输入策略名称", trigger: "blur"}
        ],
        targetType: [
          {required: true, message: "请选择目标类型", trigger: "change"}
        ],
        paramType: [
          {required: true, message: "请选择参数类型", trigger: "change"}
        ],
        isGeneral: [
          {required: true, message: "请选择是否通用", trigger: "blur"}
        ],
        StartTime: [
          {required: true, message: "请选择起始时间", trigger: "blur"}
        ],
        EndTime: [
          {required: true, message: "请选择截止时间", trigger: "blur"}
        ],
        enable: [
          {required: true, message: "请选择是否启用", trigger: "blur"}
        ],
      },
      selectedZoneObj: undefined,
      selectedTerminalsObj: undefined,
      editingTargetId: undefined
    };
  },
  created() {
    this.getList();
    this.screenHeight = document.body.clientHeight
  },
  computed: {
    getAvailableHeight() {
      return this.screenHeight - 236
    },
  },
  methods: {
    /** 查询报警策略列表 */
    getList() {
      this.loading = true;
      listStrategyParams(this.queryParams).then(response => {
        this.strategyParamsList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        tenantId: null,
        strategyName: null,
        targetType: null,
        paramType: null,
        isGeneral: 1,
        targetId: null,
        startDate: null,
        endDate: null,
        StartTime: '2022-02-02 00:00:00',
        EndTime: '2022-02-02 23:59:59',
        level1Up: null,
        level1Down: null,
        level2Up: null,
        level3Up: null,
        enable: 1,
        remark: null
      };
      this.resetForm("form");
      this.selectedZoneObj = undefined
      this.selectedTerminalsObj = undefined
      this.editingTargetId = undefined
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.ID)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加报警策略";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const ID = row.id || this.ids
      getStrategyParams(ID).then(response => {
        this.form = response.data;
        if (response.data.isGeneral === 0 && response.data.targetId.length) {
          this.editingTargetId = response.data.targetId
          this.form.targetId = response.data.targetName
        }

        this.open = true;
        this.title = "修改报警策略";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
          if (valid) {
            if (this.form.id != null) {
              if (this.form.isGeneral === 0) {
                if (this.form.targetType === '4' && this.selectedTerminalsObj) {
                  this.form.targetId = this.selectedTerminalsObj.terminalID
                } else if (this.selectedZoneObj) {
                  this.form.targetId = this.selectedZoneObj.areaId
                } else {
                  this.form.targetId = this.editingTargetId
                }
              }
              updateStrategyParams(this.form).then(response => {
                if (response.code === 200) {
                  this.$modal.msgSuccess("修改成功");
                  this.open = false;
                  this.getList();
                } else {
                  this.open = false;
                  this.$modal.msgError(response.msg);
                }
              });
            } else {
              if (this.form.isGeneral === 0) {
                if (!this.form.targetId) {
                  this.$message.error('您现在添加的是非通用报警策略，请选择报警对象')
                  return
                } else {
                  this.form.targetId = (this.form.targetType === '4' ? this.selectedTerminalsObj.terminalID : this.selectedZoneObj.areaId)
                }
              }
              addStrategyParams(this.form).then(response => {
                if (response.code === 200) {
                  this.$modal.msgSuccess("新增成功");
                  this.open = false;
                  this.getList();
                } else {
                  this.open = false;
                  this.$modal.msgError(response.msg);
                }
              });
            }
          }
        }
      )
      ;
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const IDs = row.id || this.ids;
      this.$modal.confirm('是否确认删除所选报警策略？').then(function () {
        return delStrategyParams(IDs);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('params/strategyParams/export', {
        ...this.queryParams
      }, `strategyParams_${new Date().getTime()}.xlsx`)
    },
    handleTargetTypeChange(val) {
      this.form.paramType = null
      this.form.targetId = null
      this.$refs.form.clearValidate()
      this.selectedZoneObj = undefined
      this.selectedTerminalsObj = undefined
    },
    handleTargetIdSelectClick() {
      if (this.form.targetType == undefined) {
        this.$message.error('请先选择目标类型')
      } else if (this.form.targetType === '4') {
        this.$refs.refStrategyAllTerminalSelector.openDialog()
      } else {
        this.$refs.refStrategyRegionSingleSelector.openDialog(this.form.targetType)
      }
    },
    handleRegionSelected(region) {
      this.selectedZoneObj = region
      this.form.targetId = region.areaName
    },
    handleTerminalSelected(terminal) {
      this.selectedTerminalsObj = terminal
      this.form.targetId = terminal.terminalName
    },
  }
};
</script>
